/**
 * 登录相关整合
 */

import Taro from "@tarojs/taro";
import useFetch from "@/hooks/useFetch";
import ApiUser from "./user";

import {
  ACCESSEXPIRE,
  ACCESSTOKEN,
  XP_OPENID,
  XP_UNIONID,
} from "@/utils/constant";
import { TUserInfo } from "@/global";
import useApp from "@/stores/app";

/**
 * 获取OpenId
 *
 * @param refresh - boolean 刷新
 */
async function getOpenId(refresh: boolean = false) {
  // 1. 不刷新情况下，读取storage
  if (!refresh) {
    const openid = Taro.getStorageSync(XP_OPENID);
    const unionid = Taro.getStorageSync(XP_UNIONID);

    if (!refresh && openid && unionid) {
      return { openid, unionid };
    }
  }

  // 3. 获取code
  const { code } = await Taro.login();

  // 4. 获取新的openid和unionid
  const { data } = await useFetch<{ openid: string; unionid: string }>(
    ApiUser.code2session,
    { defaultParams: { code } },
    { token: false }
  );

  Taro.setStorageSync(XP_OPENID, data.value.openid);
  Taro.setStorageSync(XP_UNIONID, data.value.unionid);

  return data.value;
}

/**
 * 通过UniId登录
 */
async function loginByUnionId(unionId: string) {
  const { data } = await useFetch<{
    accessToken: string;
    accessExpire: string;
  }>(
    ApiUser.login,
    { defaultParams: { unionId, loginType: 3 } },
    { hiddenToast: true, token: false }
  );

  if (data.value.accessToken) {
    Taro.setStorageSync(ACCESSTOKEN, data.value.accessToken);
    Taro.setStorageSync(ACCESSEXPIRE, data.value.accessExpire);
    getUserInfo();
  }
}

// 获取用户信息并保存
export const getUserInfo = async () => {
  console.log("====获取用户信息!", ApiUser.userInfo);
  const { data } = await useFetch<{ userInfo: TUserInfo }>(ApiUser.userInfo);
  const info = data.value.userInfo;

  // 这里更新，需要通知其他地方
  useApp().userInfo = info;
  return info;
};

// 静默登录尝试入口
export const SilentAuthLogin = async (changePending: boolean = true) => {
  // 1. 检查是否有登录态
  if (useApp().isLoginPending) {
    return "pending";
  }

  // 登录开始
  if (changePending) {
    useApp().isLoginPending = true;
  }

  // 1. 获取OpenID
  const data = await getOpenId();

  // 2. 去登录
  await loginByUnionId(data.unionid);

  if (changePending) {
    // 登录完成
    useApp().isLoginPending = false;
  }

  return "success";
};
